import { useState, useEffect, useCallback } from 'react';
import { User } from '../g-types/user';
import { getLocalStorage, setLocalStorage, removeLocalStorage } from '../g-utils/storage';

interface AuthState {
  token: string | null;
  user: User | null;
  isLoggedIn: boolean;
}

/**
 * 认证自定义Hook
 * @returns 认证状态和方法
 */
export function useAuth() {
  const [authState, setAuthState] = useState<AuthState>({
    token: getLocalStorage<string>('token', null),
    user: getLocalStorage<User>('user', null),
    isLoggedIn: !!getLocalStorage<string>('token', null),
  });

  // 登录
  const login = useCallback((token: string, user: User) => {
    setLocalStorage('token', token);
    setLocalStorage('user', user);
    
    setAuthState({
      token,
      user,
      isLoggedIn: true,
    });
  }, []);

  // 注销
  const logout = useCallback(() => {
    removeLocalStorage('token');
    removeLocalStorage('user');
    
    setAuthState({
      token: null,
      user: null,
      isLoggedIn: false,
    });
  }, []);

  // 更新用户信息
  const updateUser = useCallback((user: User) => {
    setLocalStorage('user', user);
    
    setAuthState((prev) => ({
      ...prev,
      user,
    }));
  }, []);

  // 检查是否有权限
  const hasPermission = useCallback(
    (permission: string | string[]) => {
      const { user } = authState;
      
      if (!user || !user.permissions) {
        return false;
      }
      
      if (Array.isArray(permission)) {
        return permission.some((p) => user.permissions?.includes(p));
      }
      
      return user.permissions.includes(permission);
    },
    [authState]
  );

  // 检查是否有角色
  const hasRole = useCallback(
    (role: string | string[]) => {
      const { user } = authState;
      
      if (!user || !user.role) {
        return false;
      }
      
      const userRoles = Array.isArray(user.role) ? user.role : [user.role];
      
      if (Array.isArray(role)) {
        return role.some((r) => userRoles.includes(r));
      }
      
      return userRoles.includes(role);
    },
    [authState]
  );

  return {
    ...authState,
    login,
    logout,
    updateUser,
    hasPermission,
    hasRole,
  };
} 